package com.yuanheng100.ems4j.common.ext;

import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by j4love on 2016/12/13.
 * Description : 状态类
 */
public abstract class Status<K,V> implements Serializable{

    private K statusValue;

    private V statusDescription;

    private Map<K,Status> statusMap;

    protected Status(){

    }

    protected Status(K statusValue,V statusDescription){
        this.statusValue = statusValue;
        this.statusDescription = statusDescription;
    }

    /**
     *
     * @param clazz
     * @param <K>
     * @return
     */
    public static <K> Map<K,? extends Status> getStatusMap(Class<? extends Status> clazz){

        Map<K,Status> statusMap = new HashMap<K,Status>();
        try {
            Constructor<? extends Status> defaultContructor = clazz.getDeclaredConstructor();
            defaultContructor.setAccessible(true);
            Status status = defaultContructor.newInstance();
            Field[] declaredFields = clazz.getDeclaredFields();
            for (Field declaredField : declaredFields) {
                declaredField.setAccessible(true);
                Object obj = declaredField.get(status);
                if(obj instanceof Status){
                    Status sta = (Status) obj;
                    statusMap.put((K)sta.getStatusValue(),sta);
                }

            }
        } catch (Exception e) {
            
        }
        return statusMap;
    }

    /**
     * 根据指定的唯一状态值获取对应的状态实体
     * @param statusValue
     * @return
     */
    public static <K> Status getStatusByUniquenessValue(K statusValue,Class<? extends Status> clazz){

        Map<Object, ? extends Status> statusMap = getStatusMap(clazz);
        return getStatusMap(clazz).get(statusValue);
    }

    /**
     * 根据指定的唯一状态值获取对应状态描述
     * @param statusValue
     * @return
     */
    public static <K,V> V getStatusDescriptionByUniquenessValue(K statusValue,Class<? extends Status> clazz){

        return (V) getStatusByUniquenessValue(statusValue,clazz).getStatusDescription();
    }

    public K getStatusValue() {
        return statusValue;
    }

    public V getStatusDescription() {
        return statusDescription;
    }
}
